package com.example.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.constant.SystemConstant;
import com.example.entity.*;
import com.example.service.IAdminService;
import com.example.util.JwtUtils;
import com.example.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员Controller
 */
@RestController("/admin")
public class AdminController {

    @Autowired
    private IAdminService adminService;



    /**
     * 根据条件分页查询后台用户信息
     * @param pageBean
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        System.out.println(pageBean);
        String query=pageBean.getQuery().trim();
        Page<Admin> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        Page<Admin> pageResult = adminService.page(page, new QueryWrapper<Admin>().like(StringUtil.isNotEmpty(query), "userName", query));
        Map<String,Object> map=new HashMap<>();
        map.put("adminList",pageResult.getRecords());
        map.put("total",pageResult.getTotal());
        return R.ok(map);
    }
    /**
     * 添加或者修改
     * @param admin
     * @return
     */
    @RequestMapping("/save")
    public R save(@RequestBody Admin admin){
        if(admin.getId()==null || admin.getId()==-1){
            adminService.save(admin);
        }else{
            adminService.saveOrUpdate(admin);
        }
        return R.ok();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        Admin admin = adminService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("admin",admin);
        return R.ok(map);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id")Integer id){
        adminService.removeById(id);
            return R.ok();

    }

    //批量删除
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            adminService.removeById(id);
            }
        return R.ok();
    }


    @PostMapping("/modifyPassword")
    public R modifyPassword(@RequestBody Admin admin){
        if (StringUtil.isEmpty(admin.getUserName())) {
            return R.error("用户名不能为空");
        }
        if (StringUtil.isEmpty(admin.getPassword())) {
            return R.error("新密码不能为空");
        }
        adminService.update(new UpdateWrapper<Admin>().set("password",admin.getNewPassword()).eq("userName",admin.getUserName()));
        return R.ok();
    }


}
